package cc.minos.servers.openfire.managers
{
	import cc.minos.servers.openfire.chats.GroupChat;
	import cc.minos.servers.openfire.chats.SimpleChat;
	import cc.minos.servers.openfire.events.ChatEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import org.igniterealtime.xiff.core.UnescapedJID;
	
	/**
	 * ...
	 * @author Minos
	 */
	public class ChatManager extends BasicManager
	{
		private var chats:Object = {};
		private var queuedRooms:Array = [];
		private var autoJoinTimer:Timer;
		
		public function ChatManager()
		{
			super( null );
		}
		
		public function joinGroupChat( jid:UnescapedJID , activate:Boolean = true , password:String = null ):GroupChat
		{
			if ( !jid )
				return null;
			var chat:GroupChat = getChat( jid ) as GroupChat;
			if ( !chat )
				chat = new GroupChat( jid );
			
			chats[ jid.bareJID ] = chat;
			
			if ( password != null )
				chat.password = password;
			
			var evt:ChatEvent = new ChatEvent( ChatEvent.CHAT_STARTED );
			evt.activate = activate;
			evt.chat = chat;
			broadcastEvent( evt );
			return chat;
		}
		
		public function startChat( jid:UnescapedJID , activate:Boolean = true ):SimpleChat
		{
			if ( !jid )
				return null;
			var chat:SimpleChat = getChat( jid ) as SimpleChat;
			if ( !chat )
				chat = new SimpleChat( jid );
			
			chats[ jid.bareJID ] = chat;
			
			var evt:ChatEvent = new ChatEvent( ChatEvent.CHAT_STARTED );
			evt.activate = activate;
			evt.chat = chat;
			broadcastEvent( evt );
			return chat;
		}
		
		public function getChat( jid:UnescapedJID ):SimpleChat
		{
			return chats[ jid.bareJID ];
		}
		
		public function closeChat( chat:SimpleChat ):void
		{
			var evt:ChatEvent = new ChatEvent( ChatEvent.CHAT_ENDED );
			evt.chat = chat;
			chat.close();
			broadcastEvent( evt );
			chats[ chat.jid.bareJID ] = null;
		}
		
		public function queueRoom( jid:UnescapedJID ):void
		{
			queuedRooms.push( jid );
			if ( !autoJoinTimer )
			{
				autoJoinTimer = new Timer( 3.0 , 1 );
				autoJoinTimer.addEventListener( TimerEvent.TIMER_COMPLETE , autoJoinRoom );
				autoJoinTimer.start();
			}
		}
		
		protected function autoJoinRoom( event:TimerEvent ):void
		{
			if ( queuedRooms.length == 0 )
				return;
			
			joinGroupChat( queuedRooms.pop() , true );
			autoJoinTimer.reset();
			autoJoinTimer.start();
		}
	
	}

}